/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.odichy.andfml.ui;

import org.odichy.andfml.R;
import org.odichy.andfml.content.FMLListFactory;
import org.odichy.andfml.domain.FMLItem;
import org.odichy.andfml.util.Constant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/**
 * AndFML, an FMyLife.com client on Google Android platform.
 *
 * @author Odin Liu<odinushuaia@gmail.com>
 *
 * @version 1.0.0
 */
public class RankViewActivity extends Activity {
	private ProgressDialog dialog;
	private ProgressThread progressThread;
	private AlertDialog alert;
	private Intent intent;
	
	private FMLListFactory factory;
	private int page = 0;
	private String category = FMLListFactory.TOP;
	private String interval = FMLListFactory.TOP;
	private int current = 0;
	private int clickItem = 0;
	private int errorTimes = 0;
	
	private final int DIALOG_WAIT = 0;
	private final int MENU_PREV = 0;
	private final int MENU_INTERVAL = 1;
	private final int MENU_NEXT = 2;
	private final int MENU_REFRESH = 7;
	
	private final int MENU_GROUP1 = 0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        this.category = bundle.getString("category");
        this.interval = this.category;
        setContentView(R.layout.basic);
        showWaitingDialog();
    }
	
	@Override
    protected Dialog onCreateDialog(int id) {
    	switch(id) {
    	case DIALOG_WAIT:
    		dialog = new ProgressDialog(this);
    		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    		dialog.setMessage(getResources().getString(R.string.waiting));
    		break;
    	default:
    		dialog = null;
    	}
    	
    	return dialog;
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(MENU_GROUP1, MENU_PREV, 0, R.string.lb_prev).setIcon(android.R.drawable.ic_media_previous);
    	menu.add(MENU_GROUP1, MENU_REFRESH, 1, R.string.lb_refresh).setIcon(android.R.drawable.ic_menu_rotate);
    	menu.add(MENU_GROUP1, MENU_INTERVAL, 2, R.string.lb_interval).setIcon(android.R.drawable.ic_menu_info_details);
    	menu.add(MENU_GROUP1, MENU_NEXT, 3, R.string.lb_next).setIcon(android.R.drawable.ic_media_next);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    	case MENU_PREV:
    		if(page>0) {
				page--;
				showWaitingDialog();
			}
			else {
				Toast.makeText(RankViewActivity.this, R.string.is_head, Toast.LENGTH_SHORT).show();
			}
    		break;
    	case MENU_REFRESH:
    		showWaitingDialog();
    		break;
    	case MENU_INTERVAL:
    		AlertDialog.Builder builder = new AlertDialog.Builder(RankViewActivity.this);
			builder.setTitle(R.string.select_interval);
			builder.setSingleChoiceItems(R.array.intervals, current, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					current = which;
					switch(current) {
					case 1:
						page = 0;
						if(category.equals(FMLListFactory.FLOP)) {
				    		interval = FMLListFactory.FLOP_DAY;
				    	}
				    	else if(category.equals(FMLListFactory.TOP)) {
				    		interval = FMLListFactory.TOP_DAY;
				    	}
						break;
					case 2:
						page = 0;
						if(category.equals(FMLListFactory.FLOP)) {
				    		interval = FMLListFactory.FLOP_WEEK;
				    	}
				    	else if(category.equals(FMLListFactory.TOP)) {
				    		interval = FMLListFactory.TOP_WEEK;
				    	}
						break;
					case 3:
						page = 0;
						if(category.equals(FMLListFactory.FLOP)) {
				    		interval = FMLListFactory.FLOP_MONTH;
				    	}
				    	else if(category.equals(FMLListFactory.TOP)) {
				    		interval = FMLListFactory.TOP_MONTH;
				    	}
						break;
					default:
						page = 0;
						if(category.equals(FMLListFactory.FLOP)) {
				    		interval = FMLListFactory.FLOP;
				    	}
				    	else if(category.equals(FMLListFactory.TOP)) {
				    		interval = FMLListFactory.TOP;
				    	}
						break;
					}
					alert.dismiss();
					showWaitingDialog();
				}
			});
			alert = builder.create();
			alert.show();
    		break;
    	case MENU_NEXT:
    		if(page<factory.getFmlList().getTotalPages()) {
				page++;
				showWaitingDialog();
			}
			else {
				Toast.makeText(RankViewActivity.this, R.string.is_foot, Toast.LENGTH_SHORT).show();
			}
    		break;
    	}
    	
    	return false;
    }
	
	private void refresh() {
		ListView listView = new ListView(this);
		TextView tv = new TextView(this);
    	StringBuilder sb = new StringBuilder();
    	sb.append(getResources().getString(R.string.tabview_label));
    	sb.append(" - ");
    	sb.append(category);
    	sb.append("  (page ");
    	sb.append(page+1);
    	sb.append("/");
    	sb.append(factory.getFmlList().getTotalPages()+1);
    	sb.append(")");
    	tv.setText(sb.toString());
    	tv.setTextColor(R.color.text);
    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
    	listView.addHeaderView(tv);
    	if(factory!=null&&factory.getFmlList()!=null) {
    		listView.setAdapter(new SimpleAdapter(this, factory.getFmlList().getFMLListForListView(), R.layout.fmls, new String[] {FMLItem.TEXT, FMLItem.AGREE, FMLItem.DESERVED, FMLItem.COMMENTS}, new int[] {R.id.fml_title, R.id.agree,R.id.deserved, R.id.comment}));
    		listView.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO to view an fml
					if(position==0) {
						return;
					}
					clickItem = position-1;
					AlertDialog.Builder builder = new AlertDialog.Builder(RankViewActivity.this);
					builder.setTitle(R.string.share_title);
					builder.setItems(R.array.shares, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch(which) {
							case 0:
							//SMS
								intent = new Intent(Intent.ACTION_VIEW);
								intent.setType("vnd.android-dir/mms-sms");
								intent.putExtra("sms_body", factory.getFmlList().getFML(clickItem).getDecodeText());
								startActivity(intent);
								break;
							case 1:
							//E-Mail
								//TODO Via more emails
								intent = new Intent(Intent.ACTION_SEND);
								intent.putExtra(android.content.Intent.EXTRA_TEXT, factory.getFmlList().getFML(clickItem).getDecodeText());
								intent.setType("message/rfc882");
								startActivity(Intent.createChooser(intent, "Send mail..."));
								//startActivity(intent);
								break;
							}
						}
					});
					alert = builder.create();
					alert.show();
					
				}
    		});
    		listView.setItemsCanFocus(true);
    	}
    	
    	dismissDialog(DIALOG_WAIT);
    	
    	setContentView(listView);
	}
	
	private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (factory.getFmlList()!=null){
                progressThread.setState(ProgressThread.STATE_DONE);
                refresh();
            }
            else {
            	Log.i("------AndFML-------", factory.getErrorMessage());
            	errorTimes++;
            	if(errorTimes>20) {
            		progressThread.setState(ProgressThread.STATE_DONE);
            		dismissDialog(DIALOG_WAIT);
            	}
            }
        }
    };
    
    /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        private Handler mHandler;
        final static int STATE_DONE = 0;
        final static int STATE_RUNNING = 1;
        private int mState;
       
        ProgressThread(Handler h) {
            mHandler = h;
        }
       
        public void run() {
            mState = STATE_RUNNING;
            factory = new FMLListFactory(Constant.VIEW_BASE_URL, interval, page, Constant.KEY, Constant.LANGUAGE_EN);
            while (mState == STATE_RUNNING) {
            	mHandler.sendEmptyMessage(0);
            }
        }
        
        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }
    }
    
    private void showWaitingDialog() {
    	showDialog(DIALOG_WAIT);
        progressThread = new ProgressThread(handler);
        progressThread.start();
    }
}
